package org.ccay.core.request.impl;

import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.IRequestContext;

/**
 * RequestContext 管理器，仅供框架API使用，业务代码不允许调用此类的API
 * @author chaowangbang
 * @since 2011-8-31
 */
public final class RequestContextManager {
	private RequestContextManager(){
	}
	
	private static final ILogger log = CcayLoggerFactory.getLogger(RequestContextManager.class);
	private static final ThreadLocal<IRequestContext> tl = new ThreadLocal<IRequestContext>();
	/**
	 * 获取当前的IRequestContext
	 * @return current
	 */
	public static IRequestContext getCurrent() { 
		return getCurrent(false);
	}
	
	/** 
	 * 获取当前的IRequestContext
	 * @param allowNull 允许空的上下文
	 * @return
	 */
	public static IRequestContext getCurrent(boolean allowNull) { 
		IRequestContext irc = tl.get();
		if(irc == null && !allowNull){
			log.warn("IRequestContext is null");
			throw new NoRequestContextException();
		}
		
		return irc;
	}
	
	

	/**
	 * 设置IRequestContext
	 * @param current 要设置的 current
	 */
	public static void setCurrent(IRequestContext current) {
		tl.set(current);
	}
	
	/**
	 * 清除IRequestContext
	 */
	public static void removeCurrent(){
		log.trace("Before clear current RequestContext.");
		tl.remove();
	}
}
